#!/bin/sh

add_rule() {
	#openvpnport=$(cat /usr/libexec/softethervpn/vpn_server.config 2>/dev/null | grep OpenVPN_UdpPortList | awk -F " " '{print $3}')
	#[ -z "$openvpnport" ] && openvpnport=1194

	iptables -N SOFTETHER_VPN-SERVER
	iptables -I INPUT -j SOFTETHER_VPN-SERVER
	
	iptables -A SOFTETHER_VPN-SERVER -p udp -m multiport --dports 500,1701,4500 -m comment --comment "L2TP/IPSec" -j ACCEPT
	#iptables -A SOFTETHER_VPN-SERVER -p udp --dport $openvpnport -m comment --comment "OpenVPN" -j ACCEPT
	#iptables -A SOFTETHER_VPN-SERVER -p tcp --dport $openvpnport -m comment --comment "OpenVPN" -j ACCEPT
	iptables -A SOFTETHER_VPN-SERVER -p tcp --dport 5555 -j ACCEPT
	#iptables -A SOFTETHER_VPN-SERVER -p tcp --dport 8888 -j ACCEPT
	#iptables -A SOFTETHER_VPN-SERVER -p tcp --dport 992 -j ACCEPT
}

del_rule() {
	count=$(iptables -n -L INPUT 2>/dev/null | grep -c "SOFTETHER_VPN-SERVER")
	if [ -n "$count" ]; then
		until [ "$count" = 0 ]
		do
			rules=$(iptables -n -L INPUT --line-num 2>/dev/null | grep "SOFTETHER_VPN-SERVER" | awk '{print $1}')
			for rule in $rules
			do
				iptables -D INPUT $rule 2>/dev/null
				break
			done
			count=$(expr $count - 1)
		done
	fi

	iptables -F SOFTETHER_VPN-SERVER 2>/dev/null
	iptables -X SOFTETHER_VPN-SERVER 2>/dev/null
}

del_rule

enable=$(uci get homeconnect.@softether[0].enable)
if [ $enable -eq 1 ]; then
	add_rule
fi